package utils

import (
	"crypto/md5"
	"encoding/hex"
	"path/filepath"
	"ticket/internal/db"
	"ticket/internal/db/model"

	"github.com/gin-gonic/gin"
)

// GetMD5Hash 将输入字符串转换为MD5哈希值
func GetMD5Hash(text string) string {
	// 创建一个MD5哈希对象
	hasher := md5.New()

	// 将字符串写入哈希对象
	hasher.Write([]byte(text))

	// 计算哈希值
	hashBytes := hasher.Sum(nil)

	// 将哈希值转换为十六进制字符串
	hashString := hex.EncodeToString(hashBytes)

	return hashString
}

// ChangeLastPathComponent 修改路径的最后一个组件
func ChangeLastPathComponent(localpath, newLast string) string {
	dir := filepath.Dir(localpath)
	return filepath.Join(dir, newLast)
}

// 获取当前登录用户对象
func GetCurrentUser(ctx *gin.Context) (*model.User, bool) {
	userId, ok := ctx.Get("user_id")
	if !ok {
		return nil, false
	}
	user := &model.User{}
	user, err := user.GetByID(db.GormDB, userId)
	if err != nil {
		return nil, false
	}
	return user, true
}
